package a04_字符串;

/**
 * <p>
 * a04_翻转字符串里的单词复习4
 * </p>
 *
 * @author flyduck
 * @since 2025/1/8
 */
public class a04_翻转字符串里的单词复习4 {

    public static void main(String[] args) {
        a04_翻转字符串里的单词复习4 test = new a04_翻转字符串里的单词复习4();
        String s = test.reverseWords(" a  is  good   sample  ");
        System.out.println(s);
    }

    public String reverseWords(String s) {
        char[] oldChars = s.toCharArray();
        char[] newChars = removeAllSpaces(oldChars);
        reverse(newChars,0,newChars.length - 1);
        reverseEachWord(newChars);


        return new String(newChars);
    }

    private void reverseEachWord(char[] newChars) {
        int leftIdx = 0;
        int rightIdx = 0;
        while (rightIdx < newChars.length) {
            if(rightIdx == newChars.length - 1 || newChars[rightIdx + 1] == ' '){
                reverse(newChars, leftIdx, rightIdx);
                leftIdx = rightIdx + 2;
                rightIdx = leftIdx;
            }else {
                rightIdx++;
            }
        }

    }

    private void reverse(char[] newChars,int leftIdx,int rightIdx) {
        while (leftIdx < rightIdx) {
            char temp = newChars[leftIdx];
            newChars[leftIdx]= newChars[rightIdx];
            newChars[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

    private char[] removeAllSpaces(char[] oldChars) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < oldChars.length) {
            if(oldChars[fastIdx] != ' '){
                if (slowIdx != 0) {
                    oldChars[slowIdx] = ' ';
                    slowIdx++;
                }
                while (fastIdx < oldChars.length && oldChars[fastIdx] != ' ') {
                    oldChars[slowIdx] = oldChars[fastIdx];
                    slowIdx++;
                    fastIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        return splitArray(oldChars, 0, slowIdx - 1);
    }

    private char[] splitArray(char[] chars,int leftIdx,int rightIdx){
        char[] newArray = new char[rightIdx - leftIdx + 1];
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = chars[leftIdx];
            leftIdx++;
        }
        return newArray;
    }
}
